import MathTool from "./MathTool";

import MsgDispatcher, { MsgType } from "./MsgDispatcher";
import { SavePlatformData } from "../Resource/ResourceData";
import GameAdsManager, { PlatformType } from "../Ad/GameAdsManager";
import UIManager from "../UI/UIManager";

export class LevelEndLogData {
    stageId: string;  //关卡ID 该字段必传
    stageName: string; //关卡名称  该字段必传
    userId?: string;  //用户ID 可选
    event: string;   //关卡完成  关卡进行中，用户触发的操作    该字段必传
    params?: {
        desc: string  //描述
    }
}

export class LevelStartLogData {
    stageId: string     //关卡ID 该字段必传
    stageName: string; //关卡名称  该字段必传
    userId?: string //用户ID 可选
}


export enum LogEventType {
    ShareGameCount = 'ShareGameCount',
    StartGameCount = 'StartGameCount',
    SingleRewardCount = 'SingleRewardCount',
    DoubleRewardCount = 'DoubleRewardCount',
    BackMusicCount = 'BackMusicCount',
}

export class EventTool {
    private static s_savePlatformdata: SavePlatformData;
    private static s_NetWorkType: string = "none";
    private static s_sessionId: string = "";

    private static s_wxappid:string= "wx39778cbf9f4090a1";
    private static s_appid:string= "wx39778cbf9f4090a1";//跳转过来的AppId
    
    private static s_extraData;
    private static s_appsecrect: string ="00a0e2db6b8a3ab41460500ae072a928";
    private static s_wxcanshare = false;
    private static s_currenttime = 0;
    private static s_shareCallback: Function = null;

    private static s_subjectUrl="https://subscribe.game520.com/subscribe/event?";

    public static Init()  {
        if (GameAdsManager.Instance.Platform == PlatformType.WeChat) {
            MsgDispatcher.Register(MsgType.GameLoadOver, "EventTool", EventTool.OnGameLoaded.bind(this));
            EventTool.GetLaunchdata();
            EventTool.GetWecharNetWorkType();
            EventTool.s_sessionId = MathTool.GenUUID();
            EventTool.Login();
            wx.onMemoryWarning(EventTool.CollectGc);
        }
        GameAdsManager.Instance.OnShow(EventTool.OnWxShow);
    }

    static CollectGc(){
        switch (GameAdsManager.Instance.Platform) {
            case PlatformType.WeChat:
                wx.triggerGC();
                break;
        
            default:
                break;
        }
    }

    static Login(){
        wx.login({
            success: (res) => {
                var xhr = new Laya.HttpRequest();
                xhr.http.timeout = 10000;//设置超时时间
                xhr.once(Laya.Event.COMPLETE, this, function (data) {
                    console.log(JSON.stringify(data));
                    if (data.errorCode == 0) {
                        wx.aldSendOpenid(data.openId);
                        // KongFuLoader.Instance.PlayerRoleData.PlayerId=data.openId;
                        // KongFuLoader.Instance.SetPlayerDataLocal();
                    }
                });
                var APP_URL = "https://xyx.game520.com/wx/jscode2openid?appid=" + EventTool.s_wxappid +
                    "&secret=" + EventTool.s_appsecrect + "&js_code=" + res.code;

                console.log("APP_URL=" + APP_URL);
                var headers = ["Content-Type", "application/json"];
                xhr.send(APP_URL, "{}", "get", "json", headers);
            }, pkgName: "", fail: () => { }, complete: () => { }
        });
    }


    static GetLaunchdata()  {
        var launchdata = wx.getLaunchOptionsSync();
        console.log("scene id=" + launchdata.scene + ' query=' + launchdata.query.key);
        if (launchdata.referrerInfo != undefined) {
            if (launchdata.referrerInfo.appId == undefined) {
                EventTool.s_appid = "";
                EventTool.s_extraData = "";
            }
            else  {
                EventTool.s_appid = launchdata.referrerInfo.appId;
                EventTool.s_extraData = launchdata.referrerInfo.extraData;
            }
            EventTool.HandlerOnShow(launchdata);
            //  EventTool.LogEvent("getLaunchOptionsSync"+ EventTool.s_appid);
        }
    }


    static GetWecharNetWorkType()  {
        wx.getNetworkType(
            {
                success(res) {
                    EventTool.s_NetWorkType = res.networkType;
                    console.log("get networktypesuccess " + res.networkType + " EventTool.s_NetWorkType=" + EventTool.s_NetWorkType);
                },
                fail()  { },
                complete()  { }
            }
        )
    }



    static OnWxShow(res) {
        console.log("eventtool wxShow "+JSON.stringify(res));
        if (res.referrerInfo != "undefined" && res.referrerInfo != undefined) {
            if (res.referrerInfo.appId == undefined) {
                EventTool.s_appid = "";
                EventTool.s_extraData = "";
            }
            else  {
                EventTool.s_appid = res.referrerInfo.appId;
                EventTool.s_extraData = res.referrerInfo.extraData;
            }
            if (res.query != "undefined" && res.query != undefined && res.query.key != "undefined" && res.query.key != undefined) {
                EventTool.LogEvent("OnAPPSHow from share+" + res.query.key);
            }
        }
        EventTool.HandlerOnShow(res);
        EventTool.ShareCallBack();
    }


    private static HandlerOnShow(res){
        // if (res&&res.scene&&res.scene=="1014") 
        // {
        
        //     if (res.query != "undefined" && res.query != undefined && res.query.pushId!= "undefined" && res.query.pushId!= undefined
        //     && res.query.templateId!= undefined&& res.query.templateId!= "undefined") {
        //         let url=EventTool.s_subjectUrl+"templateId="+res.query.templateId+"&openId="+
        //         KongFuLoader.Instance.PlayerRoleData.PlayerId+"&subscribeEvent=CallBack_Subscribe"+"&pushId="+res.query.pushId;
        //         var xhr = new Laya.HttpRequest();
        //         xhr.http.timeout = 3000;//设置超时时间；
        //         xhr.once(Laya.Event.ERROR, this, errorHandler);
        //         var headers = ["Content-Type", "application/json"];
        //         xhr.send(url, null,"get","json", headers); 
        //         console.log(url);
        //         function errorHandler(data) {
        //              console.error("requestSubscribeMessage error " + JSON.stringify(data));
        //         }
        //     }
        //     else{
        //         console.warn("模板跳转缺少 pushid 或templateid");
        //     }
        // }
    }


    public static LogEvent(evtName: string)  {
        let platform = GameAdsManager.Instance.Platform;
        if (EventTool.s_savePlatformdata == null)  {
            //  EventTool.s_savePlatformdata=Laya.loader.getRes(ResourceLoader.s_SavePlatformDataJsonPath);
        }
        console.log("LogEvent " + platform.toString() + " " + evtName);

        switch (platform) {
            case PlatformType.WeChat:
                wx.aldSendEvent(evtName);
                EventTool.LogWXEventToMysql(evtName);
                var sdk = GameGlobal.tdAppSdk;
                sdk.event({ id: evtName });
                break;
            case PlatformType.FaceBook:
                FBInstant.logEvent(evtName);
                break;

            default:
                break;
        }
    }


    public static ShareWithFriend(callback: Function, value: string = "")  
    {
        // EventTool.s_shareCallback = callback;
        // EventTool.s_wxcanshare = true;
        // EventTool.s_currenttime = new Date().getTime();
        // let wechatShareInfo = KongFuLoader.Instance.GetWxShareData();
        // if (wechatShareInfo.length < 1) {
        //     return;
        // }
        // let index = MathTool.GetRandomInt(0, wechatShareInfo.length);
        // switch (GameAdsManager.Instance.Platform) {
        //     case PlatformType.WeChat:
        //         wx.shareAppMessage(
        //             {
        //                 title: wechatShareInfo[index].Title,
        //                 imageUrl: wechatShareInfo[index].ImageUrl,
        //                 query: "key=" + wechatShareInfo[index].ImageId + "&sharekey=" + value
        //             })
        //         break;
        //     case PlatformType.QQ:
        //         qq.shareAppMessage({
        //             title: wechatShareInfo[index].Title,
        //             imageUrl:wechatShareInfo[index].ImageUrl,
        //             query:"key="+wechatShareInfo[index].ImageId+"&sharekey="+value,
        //         });
        //         break;
        //     case PlatformType.FaceBook:
        //         console.log("Fb Share Game");
        //         break;
        //     default:
        //         callback && callback(true);
        //         break;
        // }
    }


    private static ShareCallBack()  {
        if (!EventTool.s_wxcanshare)
            return;
        EventTool.s_wxcanshare = false;
        console.log("fail WxShareCallBack");
        let currenttime = new Date().getTime();
        let success = currenttime - EventTool.s_currenttime > 3000;
        console.log("Laya.timer.currTimer=" + currenttime + " this.m_currenttime=" + EventTool.s_currenttime + "success=" + success);

        if (success) {
            EventTool.s_shareCallback && EventTool.s_shareCallback(true);
        //    UIManager.Instance.ShowInterView(TipView.name,"分享成功！");
        }
        //todo 显示提示框
        else {
            EventTool.s_shareCallback && EventTool.s_shareCallback(false);
            // UIManager.Instance.ShowInterView(TipView.name, "分享失败，请重新分享!");
        }
        EventTool.s_shareCallback = null;
    }


    static LogWXEventToMysql(eventId: string)  {

        //数据写入到数据库
        if (EventTool.s_savePlatformdata != null)  {
            let time = Laya.Browser.now() / 1000;
            let timeint = time.toFixed(0);
            let timenum = parseInt(timeint);
            EventTool.s_savePlatformdata.client_ts = timenum;
            EventTool.s_savePlatformdata.connection_type = EventTool.s_NetWorkType;
            EventTool.s_savePlatformdata.device = GameAdsManager.Instance.AdsSystemInfo.model;
            EventTool.s_savePlatformdata.event_id = eventId;
            EventTool.s_savePlatformdata.manufacturer = GameAdsManager.Instance.AdsSystemInfo.brand;
            EventTool.s_savePlatformdata.os_version = GameAdsManager.Instance.AdsSystemInfo.system;
            EventTool.s_savePlatformdata.platform = GameAdsManager.Instance.AdsSystemInfo.platform;
            EventTool.s_savePlatformdata.sdk_version = GameAdsManager.Instance.AdsSystemInfo.SDKVersion;

            EventTool.s_savePlatformdata.session_id = EventTool.s_sessionId;
            EventTool.s_savePlatformdata.session_num = 1;
            // EventTool.s_savePlatformdata.user_id = KongFuLoader.Instance.PlayerRoleData.PlayerId;
            EventTool.s_savePlatformdata.d0 = EventTool.s_appid;
            if (EventTool.s_extraData == undefined) {
                EventTool.s_savePlatformdata.d1 = "no extradata";
            } else {
                EventTool.s_savePlatformdata.d1 = EventTool.s_extraData;
            }

            var xhr = new Laya.HttpRequest();
            xhr.http.timeout = 3000;//设置超时时间；
            xhr.once(Laya.Event.COMPLETE, EventTool, completeHandler);
            xhr.once(Laya.Event.ERROR, EventTool, errorHandler);
            xhr.on(Laya.Event.PROGRESS, EventTool, processHandler);

            var GAME_APP_URL = "https://data.game520.com/game/event/v1_0/json";

            var messagedata = JSON.stringify(EventTool.s_savePlatformdata);
            console.log("messagedata=" + messagedata);
            var headers = ["Content-Type", "application/json"];
            xhr.send(GAME_APP_URL, messagedata, "post", "json", headers);

        }


        function processHandler(data) {
            console.log("LogWXEventToMysql HttpRequest process ");
        }

        function errorHandler(data) {
            console.error("LogWXEventToMysql HttpRequest error " + data);

        }
        function completeHandler(e) {
            console.log("LogWXEventToMysql HttpRequest complete ");
        }
    }


    public static OnGameLoaded()  {
        EventTool.LogEvent("GameLoaded");
    }


    public static LogLevelStartInfo(levelstartInfo: LevelStartLogData)  {
        if (GameAdsManager.Instance.Platform == PlatformType.WeChat) {
            wx.aldStage.onStart({
                stageId: levelstartInfo.stageId,
                stageName: levelstartInfo.stageName
            });
            console.log("LogLevelStartInfo " + levelstartInfo.stageName);
        }
    }

    public static LogLevelEndInfo(levelendInfo: LevelEndLogData)  {
        if (GameAdsManager.Instance.Platform == PlatformType.WeChat) {
            wx.aldStage.onEnd({
                stageId: levelendInfo.stageId,
                stageName: levelendInfo.stageName,
                event: levelendInfo.event,
            });
            console.log("LogLevelEndInfo " + levelendInfo.stageName);
        }
    }

    /** 广告类型：adtype 7.event：展现-1；点击-2；跳转成功-3；跳转失败-4 5.优先级：order*/
    public static UpLoadUserAdData(adtype:string,order:number,adappid:string ,event:string)
    {
        // let playerid=KongFuLoader.Instance.PlayerRoleData.PlayerId==""?"77777":KongFuLoader.Instance.PlayerRoleData.PlayerId;
        // let adUpLoadTestPath = "https://wxex.game520.com/prod-api/delivery_event/receive_event?arrival_ts="+Math.floor(Laya.Browser.now()/1000)+
        // "&user_id="+playerid+"&belong_appid=wx39778cbf9f4090a1&adtype="+
        // adtype+"&order="+order+"&ad_appid="+adappid+"&event="+event;

        // // console.log("UpLoadUserAdData"+adUpLoadTestPath);
        // var xhr = new Laya.HttpRequest();
        // xhr.http.timeout = 3000;//设置超时时间；
        // xhr.once(Laya.Event.COMPLETE, this, OnLoadComplete);
        // xhr.once(Laya.Event.ERROR, this, errorHandler);

        // var headers = ["Content-Type", "application/json"];
        // xhr.send(adUpLoadTestPath, null, "post", "json", headers);

        // function errorHandler(data) {
        //     console.error("UpLoadUserAdData error " + JSON.stringify(data));
        // }

        // function OnLoadComplete(data) {
        //     // console.log("UpLoadUserAdData complete " + JSON.stringify(data) );
        // }
    }


   public static Subscribesject(tempId) 
    {
        // if (GameAdsManager.Instance.Platform!=PlatformType.WeChat) {
        //     return;
        // }
        
        // var xhr = new Laya.HttpRequest();
        // xhr.http.timeout = 3000;//设置超时时间；
        // xhr.once(Laya.Event.COMPLETE, this, OnLoadComplete);
        // xhr.once(Laya.Event.ERROR, this, errorHandler);
        // var headers = ["Content-Type", "application/json"];
        // let url="";
        // wx.requestSubscribeMessage({
        //     tmplIds: [tempId],
        //     success(res) {
        //        url=EventTool.s_subjectUrl+"templateId="+tempId+"&openId="+KongFuLoader.Instance.PlayerRoleData.PlayerId+"&subscribeEvent=Success_Subscribe";
        //         console.log(url);
        //         xhr.send(url, null, "get", "json", headers);
        //     },
        //     fail(res){
        //         url=EventTool.s_subjectUrl+"templateId="+tempId+"&openId="+KongFuLoader.Instance.PlayerRoleData.PlayerId+"&subscribeEvent=Reject_Subscribe";
        //         console.log(url);
        //         xhr.send(url, null, "get", "json", headers);
        //     },
        //     complete(res) {
        //         // console.log("requestSubscribeMessage complete" + JSON.stringify(res));
        //     }
        // })

        // function errorHandler(data) {
        //      console.error("requestSubscribeMessage error " + JSON.stringify(data));
        // }

        // function OnLoadComplete(data) {
        //     // console.log("UpLoadUserAdData complete " + JSON.stringify(data) );
        // }
        // Laya.stage.off(Laya.Event.CLICK, this, this.Subscribesject);
    }

}